package dy.com.tcp;

import java.awt.print.Printable;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
    public static void main(String[] args) throws IOException {
        //监听2000端口
        ServerSocket serverSocket = new ServerSocket(2000);

        System.out.println("服务器准备就绪");
        System.out.println("服务器信息：ip：" + serverSocket.getInetAddress() + "，端口：" + serverSocket.getLocalPort());
//获得客户端
        while (true) {

            Socket client = serverSocket.accept();
            //新建线程处理请求
            ClientHandler clientHandler = new ClientHandler(client);
            clientHandler.start();
        }
    }

    /**
     * 处理客户端请求
     */
    private static class ClientHandler extends Thread {
        private Socket socket;
        private boolean flag = true;

        ClientHandler(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {
            System.out.println("客户端信息：客户端ip:" + socket.getInetAddress() + ",客户端端口：" + socket.getPort());

            try {
                //服务器输出流
                PrintStream printStream = new PrintStream(socket.getOutputStream());

                //服务器输入流
                BufferedReader socketInput = new BufferedReader(new InputStreamReader(socket.getInputStream()));

                while (flag) {
                    //读一行
                    String str = socketInput.readLine();
                    if (str.equals("bye")) {
                        flag = false;
                        printStream.println("bye");
                    } else {
                        System.out.println("客户端传来的数据：" + str);
                        printStream.println(str.length());
                    }
                }


                printStream.close();
                socketInput.close();
            } catch (IOException e) {
                e.printStackTrace();

            } finally {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("客户端已关闭");
        }

    }
}
